/*
 *  QMView.h
 *  QuickMatch
 *
 *  Created by Leroy Ketelaars on 8/13/09.
 *  Copyright 2009 Zombies on Fire. All rights reserved.
 *
 */

#ifndef __QM_VIEW_H__
#define __QM_VIEW_H__

#include "SDL.h"
#include "SDL_image/SDL_image.h"

/* the delegate is only here so that QMView subclasses can set the delegate of the app instance
 	effectively passing code execution back to the app main */

class QMView
{
public:
	// the functionality
	SDL_Rect		bounds;
	SDL_Event*		events;
	SDL_Surface*	scrn;
	bool			run;
	// forking overhead, don't mess with this, it's for internal use
	bool			is_fork;
	QMView*			forkbase;
	QMView*			delegate;

	int mx, my;
	
	QMView(): events(NULL), scrn(NULL), is_fork(false), mx(0), my(0), forkbase(NULL), delegate(NULL)
	{
		printf("QMView subclass instantiated @ %p\n", this);
	}
	~QMView() 
	{
		if(!is_fork)
		{
			delete events;
		}
	}
	
	void operator=(const QMView& v)
	{
		this->events = v.events;
		this->scrn = v.scrn;
		this->forkbase = v.forkbase;
		this->delegate = v.delegate;
		this->is_fork = v.is_fork;
	}
	
	virtual bool handleInteraction() = 0;
	virtual void setBounds(int x, int y, int w, int h)
	{
		this->bounds.x = x;
		this->bounds.y = y;
		this->bounds.w = w;
		this->bounds.h = h;
	}
	void forkTo(QMView* v)
	{
		if(v != NULL)
		{
			printf("Forking %p to QMView subclass @ %p\n", this, v);
			v->events = this->events; 
			v->scrn = this->scrn; 
			v->mx = this->mx; 
			v->my = this->my; 
			v->forkbase = this;
			printf(" > Set fork base to %p\n", v->forkbase);
			v->is_fork = true;
			printf(" > Forked.\n");
		}
	}
	/** load alpha'd png to SDL_Surface from disk using SDL_image */
	SDL_Surface* loadSprite(const char* file)
	{
		SDL_Surface* returnsurf = 0;
		SDL_Surface *tempImg = 0;
		SDL_RWops *rwop = 0;
		/* Opens the file and reads it into a temp image,
		 * then loads the image, assumed to be a png with an alpha channel 
		 */
		rwop = SDL_RWFromFile( file, "rb");
		if( rwop != 0 )
		{
			tempImg = IMG_LoadPNG_RW(rwop);

			Uint32 rmask, gmask, bmask, amask;
			//play nice with PowerPC machines
			if( SDL_BYTEORDER == SDL_BIG_ENDIAN )
			{
				rmask = 0x00000000;
				gmask = 0x000000ff;
				bmask = 0x0000ff00;
				amask = 0x00ff0000;
			}
			else 
			{
				rmask = 0x00ff0000;
				gmask = 0x0000ff00;
				bmask = 0x000000ff;
				amask = 0x00000000;
			}
		//	returnsurf = SDL_CreateRGBSurface(SDL_SWSURFACE, tempImg->w, tempImg->h, 32, rmask, gmask, bmask, amask);
			returnsurf = SDL_DisplayFormatAlpha(tempImg);
			SDL_FreeSurface(tempImg);
		}
		return returnsurf;
	}
};



#endif
